package com.czh.codesandbox;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.czh.codesandbox.model.ExecMessage;
import com.czh.codesandbox.model.ExecuteCodeRequest;
import com.czh.codesandbox.model.ExecuteCodeResponse;
import com.czh.codesandbox.model.JudgeInfo;
import com.czh.codesandbox.utils.ProcessUtils;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/*
 * ClassName: JavaNativeCodeSandbox
 * Package: com.czh.codesandbox
 * Description:
 *            Java原生代码沙箱
 * @Author: CZH
 * @Create: 2025
 */
public class JavaDockerCodeSandboxOld implements CodeSandbox {


    private static final String GLOBAL_CODE_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS = "Main.java";
    //执行超时时间
    private static final long TIME_OUT = 5000L;

    private static final String SECURITY_MANAGER_PATH = "D:\\java\\IDEA-Data\\intelligent-oj\\code-sandbox\\src\\main\\resources\\security";

    private static final String SECURITY_MANAGER_CLASS_NAME = "DefaultSecurityManager";

    private static final Boolean FIRST_DONE_IMAGE = true;

    /**
     * 测试方法
     *
     * @param args
     */
    public static void main(String[] args) {
        JavaDockerCodeSandboxOld javaNativeCodeSandbox = new JavaDockerCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 22", "2 3"));
        String code = ResourceUtil.readStr("testCode/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse execute = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(execute);
    }

    /**
     * 执行用户提交的代码
     *
     * @param executeCodeRequest
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
//        System.setSecurityManager(new DefaultSecurityManager());

        //获取用户输入的测试用例
        List<String> inputList = executeCodeRequest.getInputList();
        //获取用户代码
        String code = executeCodeRequest.getCode();
        //获取用户所用语言
        String language = executeCodeRequest.getLanguage();


        //1、将用户代码写入临时文件中
        //获取用户根目录
        String userDir = System.getProperty("user.dir");
        //拼接临时文件路径
        String fileName = userDir + File.separator + GLOBAL_CODE_NAME;
        //判断文件是否存在，没有则创建文件夹
        if (!FileUtil.exist(fileName)) {
            FileUtil.mkdir(fileName);
        }
        //拼接一层用户代码文件路径，这里使用UUID生成唯一的文件名，防止文件覆盖
        String userCodeFilePath = fileName + File.separator + UUID.randomUUID();
        //写入用户代码文件
        File codeFile = FileUtil.writeString(code, userCodeFilePath + File.separator + GLOBAL_JAVA_CLASS, StandardCharsets.UTF_8);

        //2、执行编译命令，得到.class文件
        String cmd = String.format("javac -encoding utf-8 %s", codeFile.getAbsolutePath());
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            ExecMessage execMessage = ProcessUtils.getProcessReturnMessage(process, "编译");
            System.out.println(execMessage);

        } catch (Exception e) {
            return getErrorResponse(e);
        }
        //3、拉取镜像，创建容器，将.class文件复制到容器中
        //创建连接
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
//        PingCmd pingCmd = dockerClient.pingCmd();
//        pingCmd.exec();

        //拉取镜像
        String img = "openjdk:8-alpine";
//        String img = "hello-world";
        if (FIRST_DONE_IMAGE) {
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(img);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {

                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像中：" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd
                        .exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("镜像拉取异常！！！");
                throw new RuntimeException(e);
            }
            System.out.println("下载完成！");
        }

        //创建容器
        CreateContainerCmd createContainerCmd = dockerClient.createContainerCmd(img);
        HostConfig hostConfig = new HostConfig();
        hostConfig.withMemory(100 * 1000 * 1000L);//设置内存
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);//设置cpu内核数
        hostConfig.setBinds(new Bind(userCodeFilePath, new Volume("/app")));//将本地目录同步到容器中，使容器能够访问
        CreateContainerResponse createContainerResponse = createContainerCmd
                .withHostConfig(hostConfig)
                .withReadonlyRootfs(true)//设置用户禁止向root根目录写文件
                .withNetworkDisabled(true)//设置容器禁止联网
                .withAttachStdin(true)//开启docker和本地控制台连接，来获取输入
                .withAttachStderr(true)//开启docker和本地控制台连接，来获取错误信息
                .withAttachStdout(true)//开启docker和本地控制台连接，来获取输出
                .withTty(true)//开启docker和本地的交互控制台,会在后台持续存在接收输入
                .exec();
        System.out.println(createContainerResponse);

        //启动容器
        String containerId = createContainerResponse.getId();
        dockerClient.startContainerCmd(containerId).exec();

        //执行java命令，运行.class文件,获取执行结果
        //docker exec infallible_goldberg java -cp /app Main 1 5
        List<ExecMessage> execMessagesList = new ArrayList<>();
        for (String inputArgs : inputList) {
            //创建计时器，计算运行时间
            StopWatch stopWatch = new StopWatch();
            //通过空格，分割输入用例
            String[] oneArgs = inputArgs.split(" ");
            //将输入用例，拼接到docker exec infallible_goldberg java -cp /app Main 后
            String[] javaCmd = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, oneArgs);
            //创建执行命令
            ExecCreateCmdResponse createCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(javaCmd)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("执行命令：" + createCmdResponse);
            ExecMessage executeMessage = new ExecMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            //获取容器Id
            String id = createCmdResponse.getId();
            //初始化运行时间
            long runingTime = 0l;
            //超时判断，默认true
            final boolean[] timeout = {true};
            //创建执行回调
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    //如果在超时时间内执行完成，会执行此方法，同时超时判断会修改为false
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errorMessage[0]);

                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }
            };
            //初始化最大运行内存
            final long[] maxMemory = {0L};
            //创建docker自带的状态查看命令
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            //执行命令
            ResultCallback<Statistics> exec = statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onStart(Closeable closeable) {
                }

                @Override
                public void onNext(Statistics statistics) {
                    System.out.println(statistics.getMemoryStats().getUsage());
                    //获取最大运行内存
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void onError(Throwable throwable) {
                }

                @Override
                public void onComplete() {
                }

                @Override
                public void close() throws IOException {
                }
            });
            statsCmd.exec(exec);
            try {
                //开始记时
                stopWatch.start();
                //开始运行代码
                dockerClient.execStartCmd(id)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MICROSECONDS);//设置超时时间，如果在超时时间内执行完成，会执行execStartResultCallback回调的（onComplete）方法，
                //结束记时
                stopWatch.stop();
                //记录运行时间
                runingTime = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setMessage(message[0]);
            executeMessage.setErrormessage(errorMessage[0]);
            executeMessage.setTime(runingTime);
            executeMessage.setMemory(maxMemory[0]);
            execMessagesList.add(executeMessage);
        }

        //4、收集输出结果
        //创建响应对象
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        //设置最大值的执行时间，以最大执行时间为基准，来判断是否超时
        long maxTime = 0;
        //遍历执行结果列表，整理输出结果
        for (ExecMessage execMessage : execMessagesList) {
            //获取执行结果中的错误信息
            String errorMessage = execMessage.getErrormessage();
            //如果存在错误信息，则直接返回错误信息
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                //设置状态码为3，表示执行失败
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(execMessage.getMessage());
            Long time = execMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        //先初步判断答案个数，如果执行结果列表的大小和输出结果的列表大小相等，则表示所有测试用例都通过了
        if (outputList.size() == execMessagesList.size()) {
            executeCodeResponse.setStatus(1);

        }
        //设置输出结果
        executeCodeResponse.setOutput(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        //5、文件清理
        //如果文件存在，则删除
//        if(codeFile.getParentFile() != null){
//            boolean del = FileUtil.del(userCodeFilePath);
//            System.out.println("删除" + (del ? "成功" : "失败"));
//        }
        return executeCodeResponse;

    }

    /**
     * 获取错误响应
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutput(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //设置状态码为2，表示沙箱出错
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
